package com.dog.modules.system.web;

import cn.hutool.core.util.StrUtil;
import com.dog.framework.core.model.JwtUser;
import com.dog.framework.core.model.PageResult;
import com.dog.framework.core.model.ResponseResult;
import com.dog.framework.log.annotation.OperateLog;
import com.dog.framework.log.enums.BusinessType;
import com.dog.framework.web.annotation.InnerAuth;
import com.dog.framework.web.util.SecurityUserUtils;
import com.dog.modules.system.convert.SysUserConvert;
import com.dog.modules.system.domain.SysUser;
import com.dog.modules.system.api.query.SysUserQuery;
import com.dog.modules.system.api.vo.SysUserPasswordVO;
import com.dog.modules.system.api.vo.SysUserVO;
import com.dog.modules.system.service.SysUserPostService;
import com.dog.modules.system.service.SysUserRoleService;
import com.dog.modules.system.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;


/**
 * 用户管理
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@RestController
@RequestMapping("/sys/user")
@AllArgsConstructor
@Tag(name = "用户管理")
public class SysUserController {
    private final SysUserService sysUserService;
    private final SysUserRoleService sysUserRoleService;
    private final SysUserPostService sysUserPostService;

    @GetMapping("/page")
    @Operation(summary = "分页")
    public PageResult<SysUserVO> page(@RequestBody @Valid SysUserQuery query) {
        PageResult<SysUserVO> page = sysUserService.page(query);
        return page;
    }


    @PostMapping("/list")
    @Operation(summary = "查询")
    public ResponseResult<List<SysUserVO>> list(@RequestBody SysUserQuery sysUserQuery) {
        return ResponseResult.success(sysUserService.list(sysUserQuery));
    }


    @InnerAuth
    @GetMapping("/find/mobile/{mobile}")
    @Operation(summary = "通过手机号码查询用户信息")
    public SysUserVO findByMobile(@PathVariable String mobile) {
        return sysUserService.getByMobile(mobile);
    }

    @InnerAuth
    @GetMapping("/find/username/{username}")
    @Operation(summary = "通过用户名称查询用户信息")
    public SysUserVO findByUsername(@PathVariable String username) {
        return sysUserService.getByUsername(username);
    }



    @GetMapping("/{id}")
    @Operation(summary = "信息")
    public ResponseResult<SysUserVO> get(@PathVariable("id") Long id) {
        SysUser entity = sysUserService.getById(id);

        SysUserVO vo = SysUserConvert.INSTANCE.convert(entity);

        // 用户角色列表
        List<Long> roleIdList = sysUserRoleService.getRoleIdList(id);
        vo.setRoleIdList(roleIdList);

        // 用户岗位列表
        List<Long> postIdList = sysUserPostService.getPostIdList(id);
        vo.setPostIdList(postIdList);

        return ResponseResult.success(vo);
    }

    @GetMapping("/info")
    @Operation(summary = "登录用户")
    public ResponseResult<JwtUser> info() {
        JwtUser user = SecurityUserUtils.getCurrentUser();
        return ResponseResult.success(user);
    }

    @PutMapping("/password")
    @Operation(summary = "修改密码")
    @OperateLog(businessType = BusinessType.UPDATE)
    public ResponseResult<String> password(@RequestBody @Valid SysUserPasswordVO vo) {
        // 原密码不正确
        JwtUser user = SecurityUserUtils.getCurrentUser();
        if (!SecurityUserUtils.matchesPassword(vo.getPassword(), user.getPassword())) {
            return ResponseResult.fail("原密码不正确");
        }

        // 修改密码
        sysUserService.updatePassword(user.getUserId(), SecurityUserUtils.encryptPassword(vo.getNewPassword()));


        return ResponseResult.success();
    }

    @PostMapping("/save")
    @Operation(summary = "保存")
    @OperateLog(businessType = BusinessType.INSERT)
    public boolean save(@RequestBody @Valid SysUserVO vo) {
        return   sysUserService.save(vo);
    }

    @PutMapping("/update")
    @Operation(summary = "修改")
    @OperateLog(businessType = BusinessType.UPDATE)
    public ResponseResult<String> update(@RequestBody @Valid SysUserVO vo) {
        // 如果密码不为空，则进行加密处理
        if (StrUtil.isBlank(vo.getPassword())) {
            vo.setPassword(null);
        } else {
            vo.setPassword(SecurityUserUtils.encryptPassword(vo.getPassword()));
        }

        sysUserService.update(vo);

        return ResponseResult.success();
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除")
    @OperateLog(businessType = BusinessType.DELETE)
    public ResponseResult<String> delete(@RequestBody List<Long> idList) {
        Long userId = SecurityUserUtils.getUserId();
        if (idList.contains(userId)) {
            return ResponseResult.fail("不能删除当前登录用户");
        }

        sysUserService.delete(idList);

        return ResponseResult.success();
    }



    @PostMapping("/import")
    @Operation(summary = "导入用户")
    @OperateLog(businessType = BusinessType.IMPORT)
    public ResponseResult<String> importExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.fail("请选择需要上传的文件");
        }
        sysUserService.importByExcel(file, "123456");

        return ResponseResult.success();
    }

    @GetMapping("/export")
    @Operation(summary = "导出用户")
    @OperateLog(businessType = BusinessType.EXPORT)
    public void export() {
        sysUserService.export();
    }
}
